package com.yxt.qmgf.number.view;

import com.yxt.qmgf.number.vo.GameState;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;

public class sudokuView {
    private GridPane gridPane;
    private TextField[][] cells;

    public sudokuView(GridPane gridPane) {
        this.gridPane = gridPane;
        this.cells = new TextField[9][9];
        initializeGrid();
    }

    private void initializeGrid() {
        gridPane.getChildren().clear();

        for (int row = 0; row < 9; row++) {
            for (int col = 0; col < 9; col++) {
                TextField cell = new TextField();
                cell.setPrefSize(40, 40);
                cell.setStyle(getCellStyle(row, col));

                // 限制输入为1-9的数字
                cell.textProperty().addListener((observable, oldValue, newValue) -> {
                    if (!newValue.matches("[1-9]?")) {
                        cell.setText(oldValue);
                    }
                });

                cells[row][col] = cell;
                gridPane.add(cell, col, row);
            }
        }
    }

    public String getCellStyle(int row, int col) {
        String style = "-fx-font-size: 16px; -fx-alignment: center; ";

        // 添加3x3宫格边框
        if (row % 3 == 0) style += "-fx-border-width: 2 1 1 1; ";
        else if (row % 3 == 2) style += "-fx-border-width: 1 1 2 1; ";
        else style += "-fx-border-width: 1 1 1 1; ";

        if (col % 3 == 0) style += "-fx-border-width: 1 1 1 2; ";
        else if (col % 3 == 2) style += "-fx-border-width: 1 2 1 1; ";
        else style += "-fx-border-width: 1 1 1 1; ";

        style += "-fx-border-color: #000000; ";
        return style;
    }

    public void updateBoard(int[][] board) {
        for (int row = 0; row < 9; row++) {
            for (int col = 0; col < 9; col++) {
                TextField cell = cells[row][col];
                if (board[row][col] != 0) {
                    cell.setText(String.valueOf(board[row][col]));
                    cell.setEditable(false);
                    cell.setStyle(getCellStyle(row, col) + "-fx-font-weight: bold; -fx-background-color: #f0f0f0;");
                } else {
                    cell.setText("");
                    cell.setEditable(true);
                    cell.setStyle(getCellStyle(row, col));
                }
            }
        }
    }

    public TextField[][] getCells() {
        return cells;
    }
}